package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.csdn.domain.CsdnArticle;
import com.ruoyi.csdn.domain.CsdnUser;
import com.ruoyi.csdn.service.ICsdnArticleService;
import com.ruoyi.csdn.service.ICsdnUserService;
import com.ruoyi.csdn.socket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask {

    @Autowired
    private ICsdnArticleService articleService;

    @Autowired
    private ICsdnUserService csdnUserService;

    // 日志对象
    private static final Logger log = LoggerFactory.getLogger(RyTask.class);

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() throws IOException {
        CsdnArticle csdnArticle = new CsdnArticle();
        csdnArticle.setDelFlag("0");
        csdnArticle.setReleaseStatus("0");
        List<CsdnArticle> csdnArticles = articleService.selectCsdnArticleList(csdnArticle);
        if (!csdnArticles.isEmpty()) {
            //根据username去重保证一个客户端同一时间只处理一个消息
            List<CsdnArticle> uniqueArticles = csdnArticles.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    CsdnArticle::getCsdnUsername,
                                    article -> article,
                                    (existing, replacement) -> existing
                            ),
                            map -> new ArrayList<>(map.values())
                    ));

            for (CsdnArticle article : uniqueArticles) {
                LocalDateTime releaseTime = article.getReleaseTime();
                LocalDateTime now = LocalDateTime.now();
                if (now.isBefore(releaseTime) || now.isEqual(releaseTime)) {
                    log.info("未到达执行时间");
                } else {
                    log.info("当前时间 {} 大于等于发布时间 {}", now, releaseTime);
                    log.info("发布文章id {}", article.getId());
                    String csdnUsername = article.getCsdnUsername();
                    CsdnUser csdnUser = new CsdnUser();
                    csdnUser.setCsdnUsername(csdnUsername);
                    // 根据用户名查询用户是否有客户端链接
                    List<CsdnUser> csdnUsers = csdnUserService.selectCsdnUserList(csdnUser);
                    if (!csdnUsers.isEmpty()) {
                        CsdnUser csdnUser1 = csdnUsers.get(0);
                        String clientId = csdnUser1.getClient();
                        if (clientId != null && !clientId.isEmpty()) {
                            JSONObject jsonObject = new JSONObject();
                            JSONObject data = getData(article);
                            jsonObject.put("message", data);
                            jsonObject.put("type", 1);
                            WebSocketServer.sendInfo(JSON.toJSONString(jsonObject), clientId);
                        } else {
                            log.info("用户: {} 没有客户端链接", csdnUsername);
                        }
                    }
                }
            }
        }
//        System.out.println("执行无参方法");
    }

    private static JSONObject getData(CsdnArticle article) {
        JSONObject data = new JSONObject();
        data.put("id", article.getId());
        //标题
        data.put("title", article.getArticleTitle());
        //内容
        data.put("content", article.getArticleContent());
        //标签
        data.put("tags", article.getArticleTag());
        //摘要
        data.put("summary", article.getArticleAbstract());
        //类型
        data.put("type", article.getArticleSource());
        //可见范围
        data.put("visibility", article.getArticleScope());
        return data;
    }
}
